package com.itheima.common.shiro.session;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/14 14:11
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    protected static final String JWTSTR="Bearer ";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //从头信息中获取sessionId
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        if (StringUtils.isEmpty(id)) {
            //为空，调用父类生成一个 sessionId返回
            return super.getSessionId(request, response);
        }else{
            //不为空
            id=id.replaceAll(JWTSTR,"");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        }
    }
}
